<?php
declare (strict_types = 1);

namespace app\backmanage\controller;

use app\middleware\Auth;
use think\facade\Request;

class Base
{
    protected $middleware = [
        Auth::class
    ];

    //where 筛选
    public function buildParams($searchField = null, $alias = '')
    {
        $where = [];

        $filter = request()->param('filter');

        if (!empty($filter['keyword'])) {
            $where[] = [$searchField, 'like', '%' . $filter['keyword'] . '%'];
            unset($filter['keyword']);
        }
        if ($filter) {
            foreach ($filter as $key => $value) {
                if ($value !== '') {
                    if(strstr($key,"start_") ){
                        $where[] = [substr($key,strlen("start_")), '>=', strtotime($value)];
                    }elseif(strstr($key,"end_")){
                        $where[] = [substr($key,strlen("end_")), '<=', strtotime($value)];
                    }else{
                        $where[] = [$key, '=', $value];
                    }
                }
            }
        }
        $sort = request()->param('sort');
        $order = '';
        if ($sort) {
            foreach ($sort as $key => $value) {
                if ($value) {
                    $order = $key . ' ' . $value ?: $order . ',' . $key . ' ' . $value;
                }
            }
        }
        $order = $order ?: ($alias ? $alias . '.id desc' : 'id desc');
        $page  = request()->param('page/d', 1);

        $limit = request()->param('limit/d', 15);

        return [$where, $order, $page, $limit];
    }

    /**
     * 调用分区API接口
     * @param string $partitionId 分区ID
     * @param string $apiPath API路径 (如: '/backmanage/VipRenew/index')
     * @param array $params 请求参数
     * @param bool $removePartitionIdFromFilter 是否从filter中移除partition_id参数
     * @return array 返回格式化的响应数据
     */
    protected function callPartitionApi($partitionId, $apiPath, $params = [], $removePartitionIdFromFilter = true)
    {
        // 获取分区数据
        $partitionInfo = \app\common\model\common\PartitionPackage::where([
            'partition_id' => $partitionId,
            'status' => 1
        ])->find();

        if (empty($partitionInfo['id'])) {
            return ['code' => -1, 'msg' => '分区ID无效，请重试'];
        }

        if (empty($partitionInfo['crm_url'])) {
            return ['code' => -100, 'msg' => '该签名包未配置Crm地址'];
        }

        if ($partitionInfo['status'] != 1) {
            return ['code' => -100, 'msg' => '该分区未启用'];
        }

        // 构建API URL
        $url = $partitionInfo['crm_url'] . $apiPath;
        
        // 处理请求参数
        if (empty($params)) {
            $params = Request::param();
        }
        $params['is_check_auth'] = 2;
        
        // 移除filter中的partition_id参数
        if ($removePartitionIdFromFilter && isset($params['filter']['partition_id'])) {
            unset($params['filter']['partition_id']);
        }

        // 调用远程API
        $ret = json_decode(httpHelper($url, $params), true);

        if (!isset($ret['code'])) {
            return ['code' => -100, 'msg' => "接口数据返回异常"];
        }

        if ($ret['code'] != 0) {
            return ['code' => -100, 'msg' => $ret['msg'] ?? $ret['error_msg']];
        }

        // 为返回数据添加分区信息
        if (isset($ret['data']) && is_array($ret['data'])) {
            foreach ($ret['data'] as &$item) {
                $item['partition_id'] = $partitionInfo['partition_id'];
                $item['partition_name'] = $partitionInfo['partition_name'];
            }
        }

        return $ret;
    }

    /**
     * 获取分区包信息
     * @return array [partitionId, partitions]
     */
    protected function getPartitionPackageInfo()
    {
        return \app\common\model\common\PartitionPackage::getPartitionPackageInfo();
    }

    /**
     * 获取分区数据库连接
     * @param string $partitionId 分区ID
     * @return \think\db\Connection|false 返回数据库连接对象或false
     */
    protected function getPartitionDatabase($partitionId)
    {
        // 获取分区配置信息
        $config = \app\common\model\common\PartitionPackage::where([
            'partition_id' => $partitionId,
            'status' => 1
        ])->find();

        if (empty($config)) {
            return false;
        }

        // 调用getSwitchDatabaseModel函数获取数据库连接
        return getSwitchDatabaseModel(
            sprintf("partition_%s", $config['partition_id']),
            $config['api_mysql_host_name'],
            $config['api_mysql_database'],
            $config['api_mysql_username'],
            $config['api_mysql_password'],
            $config['api_mysql_hostport']
        );
    }

    /**
     * 获取所有分区的数据库配置
     * @return array 返回以partition_id为键的配置数组
     */
    protected function getAllPartitionConfigs()
    {
        return \app\common\model\common\PartitionPackage::where([
            'status' => 1
        ])->column([
            'partition_id',
            'api_mysql_host_name',
            'api_mysql_database',
            'api_mysql_username',
            'api_mysql_password',
            'api_mysql_hostport',
            'pc_url',
            'partition_name',
            'crm_url',
            'crm_name',
            'crm_pwd'
        ], 'partition_id');
    }

    /**
     * 批量获取多个分区的数据库连接
     * @param array $partitionIds 分区ID数组
     * @return array 返回以partition_id为键的数据库连接数组
     */
    protected function getMultiplePartitionDatabases($partitionIds)
    {
        $configs = $this->getAllPartitionConfigs();
        $databases = [];

        foreach ($partitionIds as $partitionId) {
            $config = $configs[$partitionId] ?? [];
            if (empty($config)) {
                continue;
            }

            $database = getSwitchDatabaseModel(
                sprintf("partition_%s", $config['partition_id']),
                $config['api_mysql_host_name'],
                $config['api_mysql_database'],
                $config['api_mysql_username'],
                $config['api_mysql_password'],
                $config['api_mysql_hostport']
            );

            if ($database) {
                $databases[$partitionId] = $database;
            }
        }

        return $databases;
    }
}
